import { Text, useMessage } from 'alemonjs'
import { validate, selects } from '@src/apps/index'
import { letters } from '@src/db/src/models/user/letters'
import { Op } from 'sequelize'
import { qidToUid } from '@src/apps/tools/qid_goto_uid'

export const regular = /^(!|！|\/)?邮箱/

const response = onResponse(selects, async e => {
  const UserId = await qidToUid(e.UserId ?? e.UserKey)

  const now = Date.now()

  // 先将 finish_time 小于当前时间的信件 status 批量更新为 3（已过期/已删除）
  await letters.update(
    { status: 3 },
    {
      where: {
        finish_time: { [Op.lt]: now },
        status: { [Op.ne]: 3 }
      }
    }
  )

  // 查询所有未过期信件
  const [message] = useMessage(e)
  const letterList = await letters.findAllValues({
    where: {
      uid: UserId, // 假设 user_id 是用户的唯一标识符
      status: { [Op.ne]: 3 } // 只查询未删信件
    }
  })

  if (!letterList.length) {
    const content = '\n没有任何信件哦~'
    let final_content = `\n===📬我的邮箱📬===\n———————————${content}\n———————————\n回复“/查阅+序号”查看详情`
    message.send(format(Text(final_content)))
    return
  }

  // 计算剩余时间
  const listWithRemain = letterList.map(l => {
    // finish_time 为 Date 类型，需转为时间戳再计算
    let finishTime = 0
    if (l.finish_time) {
      finishTime = new Date(l.finish_time).getTime()
      if (isNaN(finishTime)) finishTime = 0
    }
    const remain = finishTime > 0 ? finishTime - now : 0
    return { ...l, remain }
  })

  // 按剩余时间升序排序
  listWithRemain.sort((a, b) => a.remain - b.remain)

  const statusMap: Record<number, string> = {
    0: '未读',
    1: '已读',
    2: '已领',
    3: '已删'
  }

  const content = listWithRemain
    .map((l, idx) => {
      // 邮件内容只显示前4个字，超出加省略号
      let shortContent = l.content || ''
      if (shortContent.length > 4) {
        shortContent = shortContent.slice(0, 4) + '…'
      }

      // 剩余时间格式化为天、小时、分钟（向下取整，不显示秒）
      let remainText = '已过期'
      if (l.remain > 0) {
        const days = Math.floor(l.remain / (24 * 60 * 60 * 1000))
        const hours = Math.floor(
          (l.remain % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000)
        )
        const min = Math.floor((l.remain % (60 * 60 * 1000)) / 60000)
        if (days > 0) {
          remainText = `${days}天${hours}小时${min}分`
        } else if (hours > 0) {
          remainText = `${hours}小时${min}分`
        } else {
          remainText = `${min}分`
        }
      }

      // 判断things字段不为空且status不为2
      let thingText = ''
      if (
        l.things &&
        l.things !== '无' &&
        l.things !== '{}' &&
        l.status !== 2
      ) {
        thingText = '(有附件)'
      }

      const statusText = statusMap[l.status] ?? l.status

      return `\n${idx + 1}.【${l.title}】${shortContent}\n  ${l.from}邮件/${statusText}${thingText}\n 🗓剩余${remainText}`
    })
    .join('\n— — — — — —')

  let final_content = `\n===📬我的邮箱📬===\n———————————${content}\n———————————\n回复“/查阅+序号”查看详情`
  message.send(format(Text(final_content)))
  return
})

export default onResponse(selects, [validate, response.current])
